<?php
namespace Core\Event\Application\Annotation;
use Core\Event\Annotation;
class Output extends Annotation
{
    protected $_arguments;

    private function _filter($data, $result = []) {
        if(!($arguments = $this->_arguments) || !is_array($data)) {
            return $data;
        }
        foreach ($data as $key => $value) {
            if(is_array($value)) {
                $result[$key] = $this->_filter($value);
            }else{
                if(!in_array($key, $arguments)) {
                    unset($result[$key]);
                    continue;
                }
                $result[$key] = $value;
            }
        }
        return array_filter($result);
    }

    public function beforeSendResponse($event)
    {
        if ($returnedValue = $this->dispatcher->getReturnedValue()) {
            $this->_arguments = $this->_annotation->getArguments();
            $returnedValue = $this->_filter($returnedValue);
            if(!is_string($returnedValue)) {
                $this->response->setJsonContent($returnedValue);
            }
        }
        return true;
    }
}